﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace TfsBacklogMgr.Main
{
    public class TfsFactory : IFactory
    {

        Tfs.TfsServer _server = null;

        public void SaveSettings(Context ctx)
        {
            string filename = ctx.Filename;
            IniFile ini = new IniFile(filename);

            ini.IniWriteValue("Tfs", "Server", ctx.TfsServer);
            ini.IniWriteValue("Tfs", "Project", ctx.TfsProject);

            ini.IniWriteValue("Current", "SprintIter", ctx.CurrentSprintIteration == null ? "" : ctx.CurrentSprintIteration.Path);
            ini.IniWriteValue("Current", "BacklogIter", ctx.CurrentBacklogIteration == null ? "" : ctx.CurrentBacklogIteration.Path);

            foreach (var u in ctx.AllUsers)
            {
                ini.IniWriteValue("SelectedUsers", u.Login, u.IsChosen.ToString());
                if (!string.IsNullOrEmpty(u.ImagePath))
                    ini.IniWriteValue("Pictures", u.Login, u.ImagePath);
            }
            foreach (var i in ctx.AllIterations)
            {
                ini.IniWriteValue("BacklogIterations", i.Path, i.IsBacklogIteration.ToString() );
            }
        }

        public Context LoadSettings(string filename)
        {
            IniFile ini = new IniFile(filename);
            Context ctx = Context.GetContext();

            ctx.TfsServer = ini.IniReadValue("Tfs", "Server");
            ctx.TfsProject = ini.IniReadValue("Tfs", "Project");

            ConnectToTfs();

            foreach (var i in ctx.AllIterations)
            {
                i.IsBacklogIteration = ini.IniReadBool("BacklogIterations", i.Path);
            }

            string path = ini.IniReadValue("Current", "SprintIter");
            ctx.CurrentSprintIteration = Iteration.GetIteration(path);

            path = ini.IniReadValue("Current", "BacklogIter");
            ctx.CurrentBacklogIteration = Iteration.GetIteration(path);

            foreach (var u in ctx.AllUsers)
            {
                u.IsChosen = ini.IniReadBool("SelectedUsers", u.Login);
                string img = ini.IniReadValue("Pictures", u.Login);
                if (!string.IsNullOrEmpty(img))
                {
                    u.ImagePath = img;
                }
            }
            ctx.AddUsers();
            Context.Load();
            return ctx;
        }


        // called from TFS connect button or during context load
        // -- update the context with state from tfs server
        public void ConnectToTfs()
        {
            Context ctx = Context.GetContext();
            if (_server == null && ! string.IsNullOrWhiteSpace(ctx.TfsServer) )
            {
                Tfs.ConnectionInfo conn = new Tfs.ConnectionInfo();
                conn.TeamProjectCollectionUri = new Uri(ctx.TfsServer);
                conn.TeamProject = ctx.TfsProject;

                _server = new Tfs.TfsServer(conn);
                var isOK = _server.CheckConnectionStatus();
                if (isOK != Tfs.ConnectionStatus.Online)
                {
                    _server = null;
                    MessageBox.Show("Connection to TFS Failed");
                    return;
                }

                TfsBacklogMgr.Tfs.TfsConfig cfg = _server.DetermineConfig();
                ctx.AddWorkItemTypes();

                var iters = _server.GetAllIterations();
                foreach (string iter in iters)
                    Iteration.GetIteration(iter);

                Iteration root = Iteration.GetIteration("$");
                root.IsBacklogIteration = true;
                
                var users = _server.GetAllUsers();
                int id = 1;
                foreach (var val in users)
                {
                    User tmp = new User() { Id = id++, Login = val.Key, Name = val.Value };
                    User.Add(tmp);
                }

                LoadWorkItems();

                Context.Load();
            }
        }

        public void LoadWorkItems()
        {
            ConnectToTfs();
            var items = _server.GetAllWorkItems();
            foreach (Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem item in items)
            {
                string WIT = item.Type.Name;
                if ( string.Compare(WIT, Context.GetContext().WIT_Story, true) == 0 ||
                    string.Compare(WIT, Context.GetContext().WIT_Task, true) == 0 ||
                    string.Compare(WIT, Context.GetContext().WIT_Bug, true ) == 0 )
                {
                    _server.AddAllowedStates(item);
                    WorkItem wi = new WorkItem(item);
                    WorkItem.Add(wi);
                }
            }
        }

        public List<StateAndReason> GetNextStatesFor(string WIT, string curState)
        {
            return _server.GetNextStatesFor(WIT, curState);
        }

        public string WITStory { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? "" : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().WITStory; } }
        public string WITTask { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? "" : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().WITTask; } }
        public string WITBug { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? "" : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().WITBug; } }

        public string WITFPoints { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? "" : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().StoryPoints; } }
        public string WITFHours { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? "" : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().OrgEstimateHrs; } }
        public string WITFRemain { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? "" : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().RemainingHrs; } }

        public int PointsPrecision { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? 0 : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().StoryPointsPrecision; } }
        public int HoursPrecision { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? 0 : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().OrgEstimateHrsPrecision; } }
        public int RemainPrecision { get { return TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig() == null ? 0 : TfsBacklogMgr.Tfs.TfsConfig.GetTfsConfig().RemainingHrsPrecision; } }

#if false
         public static Iteration GetIteration(string path)
        {
            if (_iters.ContainsKey(path))
                return _iters[path];
            else
            {
                var newIter = new Iteration(path);
                _iters[path] = newIter;
                var parent = newIter.Parent;
                return _iters[path];
            }
        }

        public static List<Iteration> GetIterations(string path)
        {
            Iteration iter = GetIteration(path);
            return iter.Children;
        }
#endif
    }
}
